<template>
  <div class = "">
    <!--  //头部-->
    <el-form
        :inline="true"
        :model="selectByForm"
        class="advanced-form"
        label-position="right"
    >
      <el-row :gutter="20" class="form-row">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="土地" class="form-item">
            <el-input
                v-model="selectByForm.used"
                placeholder="请输入土地名"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="项目" class="form-item">
            <el-input
                v-model="selectByForm.revenueName"
                placeholder="请输入收益项目名称"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="总价" class="form-item">
            <el-input
                v-model="selectByForm.totalAmount"
                placeholder="请输入收益总价"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="姓名" class="form-item">
            <el-input
                v-model="selectByForm.recorderName"
                placeholder="请输入取得收益人姓名"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮（单独一行） -->
      <el-row>
        <el-col :span="24" class="form-actions">
          <el-button type="primary" @click="onSelect" icon="el-icon-search">查询</el-button>
          <el-button
              type="success"
              @click="toAdd"
              icon="el-icon-plus"
              plain
          >新增
          </el-button>
        </el-col>
      </el-row>
    </el-form>

    <!--  列表页  -->
    <el-table :data="tableData"
              style="width: 100%"
              :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
              stripe
              highlight-current-row
              @current-change="toShow"
              border
    >
      <el-table-column prop="used" label="土地名" width="180" align="center"  ></el-table-column>
      <el-table-column prop="revenueName" label="项目名称" width="180" align="center" ></el-table-column>
      <el-table-column prop="quantity" label="项目数量" width="180" align="center" ></el-table-column>
      <el-table-column prop="unitPrice" label="项目单价" width="180" align="center" ></el-table-column>
      <el-table-column prop="totalAmount" label="项目总支出" width="180" align="center" ></el-table-column>
      <el-table-column prop="transactionDate" label="交易时间" width="180" align="center" >
        <template slot-scope="scope">
          {{ scope.row.transactionDate ? scope.row.transactionDate.split('T')[0] : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="recorderName" label="交易人" width="180" align="center" ></el-table-column>
      <el-table-column
          prop="status"
          label="审核状态"
          width="180"
          align="center"
      >
        <template slot-scope="scope">
          <el-popover
              v-model="scope.row.statusPopoverVisible"
              placement="top"
              width="160"
              trigger="click"
          >
            <div style="text-align: center; margin: 0">
              <el-button
                  v-for="status in ['pending', 'approved']"
                  :key="status"
                  size="mini"
                  :type="getStatusButtonType(status)"
                  @click="changeStatus(scope.row, status)"
              >
                {{ statusMap[status] }}
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="showRejectDialog(scope.row)"
              >
                驳回
              </el-button>
            </div>
            <el-tag
                slot="reference"
                :type="statusTagType[scope.row.status]"
                effect="light"
                style="cursor: pointer;"
            >
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </el-popover>

          <!-- 驳回原因对话框 -->
          <el-dialog
              title="填写驳回原因"
              :visible.sync="scope.row.rejectDialogVisible"
              width="500px"
              v-if="scope.row.rejectDialogVisible"
          >
            <el-form :model="scope.row" label-width="80px">
              <el-form-item label="驳回原因">
                <el-input
                    type="textarea"
                    :rows="3"
                    v-model="scope.row.rejectReason"
                    placeholder="请输入驳回原因"
                ></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="scope.row.rejectDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmReject(scope.row)"
        >确定</el-button>
      </span>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="toUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row.revenueId)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--    页脚-->
    <el-pagination
        background
        :page-size="pageSize"
        :current-page="pageNum"
        :page-count="pages"
        layout="prev, pager, next"
        :total="total"
        @current-change="changePageNum"
    >
    </el-pagination>

    <!--    弹窗，实现新增信息-->
    <el-dialog
        title="新增农业收益"
        :visible.sync="addDialog"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="revenueForm"
          :rules="rules"
          ref="revenueForm"
          label-position="left"
          class="cost-form"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="土地用途" prop="used">
              <el-select
                  v-model="revenueForm.used"
                  placeholder="请选择土地用途"
                  filterable
                  clearable
                  remote
                  :loading="usageLoading"
                  @focus="loadLandUsageOptions"
              >
                <el-option
                    v-for="item in landUsageOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名" prop="revenueName">
              <el-input
                  v-model="revenueForm.revenueName"
                  placeholder="收益项目名称"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                  v-model="revenueForm.quantity"
                  :min="0"
                  :step="1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input-number
                  v-model="revenueForm.unitPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(元)">
              <el-input
                  :value="(revenueForm.quantity * revenueForm.unitPrice).toFixed(2)"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false" size="medium">取 消</el-button>
        <el-button
            type="primary"
            @click="addForm('revenueForm')"
            size="medium"
            :loading="submitting"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!--    弹窗，实现修改信息-->
    <el-dialog
        title="修改收益"
        :visible.sync="updateDialog"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="revenueForm"
          :rules="rules"
          ref="revenueForm"
          label-position="left"
          class="cost-form"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="土地名" prop="used">
              <el-input
                  :value="revenueForm.used"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名" prop="revenueName">
              <el-input
                  v-model="revenueForm.revenueName"
                  placeholder="收益项目名称"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                  v-model="revenueForm.quantity"
                  :min="0"
                  :step="1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input-number
                  v-model="revenueForm.unitPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(元)">
              <el-input
                  :value="(revenueForm.quantity * revenueForm.unitPrice).toFixed(2)"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false" size="medium">取 消</el-button>
        <el-button
            type="primary"
            @click="updateForm('revenueForm')"
            size="medium"
            :loading="submitting"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>


import {
  deleteRevenueApi,
  getRevenuePage,
  rejectRevenueApi,
  saveRevenueApi,
  updateRevenueApi,
  updateRevenueStatusApi
} from "@/api/revenue";
import {getLandUsageListApi} from "@/api/land";
import {updateProfitApi} from "@/api/profit";


export default {
  data() {
    return {
      // 状态映射
      statusMap: {
        pending: '待审核',
        approved: '已通过',
        rejected: '已驳回'
      },
      // 状态标签类型
      statusTagType: {
        pending: 'warning',
        processing: 'success',
        resolved: 'danger'
      },
      //筛选表单
      selectByForm: {
        used: '',
        revenueName: '',
        totalAmount: '',
        recorderName: ''
      },
      //列表数据
      tableData: '',
      //页脚
      pages: 0,
      total: 1,
      pageNum: 1,
      pageSize: 6,
      //弹窗 默认值
      addDialog: false,
      updateDialog:false,
      // ...其他数据保持不变
      rejectDialogVisible: false,
      rejectReason: '',
      submitting: false,//按钮是否可使用
      revenueForm: {
        used: '',
        revenueName: '',
        quantity: 0,//数量
        unitPrice: 0,//单价
        totalAmount: 0,//总价格
        recorderName: '',
        status:'',
        reviewID:'',
        reviewComment:''
      },
      rules: {
        used: [
          {required: true, message: '请输入土地名', trigger: 'blur'}
        ],
        revenueName: [
          {required: true, message: '请输入获益名称', trigger: 'blur'}
        ],
        quantity: [
          {required: true, message: '请输入数量', trigger: 'blur'}
        ],
        unitPrice: [
          {required: true, message: '请输入单价', trigger: 'blur'}
        ]
      },
      landUsageOptions: [], // 土地用途选项
      usageLoading: false // 加载状态
    };
  },
  methods: {

    // 显示驳回对话框
    showRejectDialog(row) {
      row.statusPopoverVisible = false;
      this.$set(row, 'rejectDialogVisible', true);
      this.$set(row, 'rejectReason', '');
    },

    // 确认驳回
    confirmReject(row) {
      if (!row.rejectReason || row.rejectReason.trim() === '') {
        this.$message.warning('请填写驳回原因');
        return;
      }

      row.rejectDialogVisible = false;

      this.$confirm(`确定驳回并填写原因吗?`, '提示', {
        type: 'warning'
      }).then(() => {
        this.costForm = row
        this.costForm.reviewComment = row.rejectReason
        // 实际项目中这里应该调用API
        rejectRevenueApi(this.costForm).then(() => {
          this.$message.success('已驳回');
          row.status = 'rejected';
        });

      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    // 获取状态按钮类型
    getStatusButtonType(status) {
      return {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger'
      }[status]
    },

    // 修改状态
    changeStatus(row, newStatus) {
      // 关闭popover
      row.statusPopoverVisible = false;

      // 如果状态没有变化，则不处理
      if (row.status === newStatus) return;

      // 这里调用API更新状态
      this.$confirm(`确定将状态修改为"${this.statusMap[newStatus]}"吗?`, '提示', {
        type: 'warning'
      }).then(() => {
        // 实际项目中这里应该调用API
        this.costForm = row
        this.costForm.status = newStatus
        updateRevenueStatusApi(this.costForm).then(async () => {
          this.$message.success('状态更新成功');
          await updateProfitApi();
          this.getPage()
        });

      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },

    // 加载土地用途选项
    async loadLandUsageOptions() {
      if (this.landUsageOptions.length > 0) return

      try {
        this.usageLoading = true
        const response = await getLandUsageListApi()
        this.landUsageOptions = response.data.map(item => ({
          value: item.landId, // 假设返回数据有id字段
          label: item.used // 假设返回数据有name字段
        }))
      } catch (error) {
        console.error('获取土地用途列表失败:', error)
        this.$message.error('获取土地用途列表失败')
      } finally {
        this.usageLoading = false
      }
    },

    toUpdate(row){
      console.log(row)
      this.revenueForm = row
      this.updateDialog = true
    },

    updateForm() {
      this.$refs.revenueForm.validate(valid => {
        if (valid) {
          this.submitting = true
          // 模拟API调用
          updateRevenueApi(this.revenueForm,sessionStorage.getItem('username')).then(()=>{
            this.submitting = false
            this.updateDialog = false
            this.$message.success('修改成功')
            this.getPage()
          })
        }
      })
    },

    //删除整条信息
    toDelete(id) {
      this.$confirm(`确定删除此条信息吗？`, '提示', {
        type: 'danger'
      }).then(() => {
        // 这里调用API更新状态
        deleteRevenueApi(id)
        this.getPage()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },

    addForm() {
      this.$refs.revenueForm.validate(valid => {
        if (valid) {
          this.submitting = true

          // 模拟API调用
          saveRevenueApi(this.revenueForm, sessionStorage.getItem('username')).then(() => {
            this.submitting = false
            this.addDialog = false
            this.$message.success('新增成功')
            this.getPage()

          })
        }
      })
    },

    toAdd() {
      this.revenueForm = {}
      this.addDialog = true
    },

    onSelect() {
      this.pageNum = 1
      this.getPage()
    },

    //获取页面数据
    getPage() {
      getRevenuePage(this.selectByForm, this.pageNum, this.pageSize).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list
          this.pages = res.data.pages
          this.total = res.data.total
          this.pageNum = res.data.pageNum
          this.pageSize = res.data.pageSize
        }
      })
    },
    //直接选择第几页
    changePageNum(v) {
      console.log(v + '')
      this.pageNum = v
      this.getPage()
    }
  },
  created() {
    this.getPage()
  }
}
</script>

<style scoped>
.form-actions {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  margin-top: 10px;
}
/* 表单行样式 */
.form-row {
  margin-bottom: 15px;
}

/* 表单列样式 */
.form-col {
  margin-bottom: 10px;
  padding: 0 10px;
}

/* 表单项样式 */
.form-item {
  margin-bottom: 0;
}

/* 输入框样式 */
.form-input {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-col {
    padding: 0 5px;
  }
}

.cost-form {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px 0;
  border-top: 1px solid #e8e8e8;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 数字输入框右侧按钮样式 */
.el-input-number__decrease,
.el-input-number__increase {
  background-color: #f5f7fa;
}
</style>

